package service

import (
	"encoding/json"
	"fmt"
	"niu-video/app/consts"
	"niu-video/app/model"
	"niu-video/app/repository"
	"niu-video/pkg/logger"
	"niu-video/pkg/rabbitmq"
	"niu-video/pkg/redis"
	"strconv"
)

var LikeService = newLikeService()

func newLikeService() *likeService {
	return &likeService{}
}

type likeService struct {
}

func (l *likeService) Like(request model.LikeAction, userId int64) string {
	// 查询有没有这个视频
	video := repository.VideoRepository.GetOne(request.VideoID)
	if video.VideoID == 0 {
		return "该视频不存在！"
	}
	switch request.ActionType {
	case 1:
		// 点赞
		l.like(request.VideoID, userId)
		// 评分转化
		UserService.UserAction(model.UserAction{
			VideoId: request.VideoID,
			Ratio:   5,
		}, userId)
		return "点赞成功！"
	case 2:
		l.unLike(request.VideoID, userId)
		// 评分转化
		UserService.UserAction(model.UserAction{
			VideoId: request.VideoID,
			Ratio:   -5,
		}, userId)
		return "您已取消点赞"
	}
	return ""
}

// 点赞
func (l *likeService) like(videoId int64, userId int64) {
	redis.Redis.Eval(consts.LuaScript, []string{
		fmt.Sprintf("%s:%d:%d", consts.REDIS_LIKE_PREFIX, videoId, userId),
		fmt.Sprintf("%s:%d", consts.REDIS_LIKE_COUNTER_PREFIX, videoId)})
	videoMessage := model.LikeMessage{
		VideoID:    videoId,
		UserID:     userId,
		ActionType: 1,
	}
	likeMessageJson, err := json.Marshal(videoMessage)
	logger.LogIf(err)
	rabbit := rabbitmq.NewRabbitMQ(consts.RABBITMQ_LIKE_EXCHANGE, consts.RABBITMQ_LIKE_ROUTE, consts.RABBITMQ_LIKE_QUEUE)
	defer rabbit.Close()
	rabbit.SendMessage(rabbitmq.Message{Body: string(likeMessageJson)})
}

// 取消点赞
func (l *likeService) IsLike(videoId int64, userId int64) bool {
	is := redis.Redis.Has(fmt.Sprintf("%s:%d:%d", consts.REDIS_LIKE_PREFIX, videoId, userId))
	if is {
		return is
	}
	like := repository.LikeRepository.GetUserLike(videoId, userId)
	if like.LikeID != 0 {
		return true
	}
	return false
}
func (l *likeService) unLike(videoId int64, userId int64) {
	redis.Redis.Eval(consts.UnLuaScript, []string{
		fmt.Sprintf("%s:%d:%d", consts.REDIS_LIKE_PREFIX, videoId, userId),
		fmt.Sprintf("%s:%d", consts.REDIS_LIKE_COUNTER_PREFIX, videoId)})
	videoMessage := model.LikeMessage{
		VideoID:    videoId,
		UserID:     userId,
		ActionType: 2,
	}
	likeMessageJson, err := json.Marshal(videoMessage)
	logger.LogIf(err)
	rabbit := rabbitmq.NewRabbitMQ(consts.RABBITMQ_LIKE_EXCHANGE, consts.RABBITMQ_LIKE_ROUTE, consts.RABBITMQ_LIKE_QUEUE)
	defer rabbit.Close()
	rabbit.SendMessage(rabbitmq.Message{Body: string(likeMessageJson)})
}

func (l *likeService) LikeCount(videoId int64) int64 {
	cntStr := redis.Redis.Get(fmt.Sprintf("%s:%d", consts.REDIS_LIKE_COUNTER_PREFIX, videoId))
	if cntStr == "" {
		return 0
	}
	cnt, err := strconv.ParseInt(cntStr, 10, 64)
	if err != nil {
		logger.ErrorString("like", "LikeCount", err.Error())
		return 0
	}
	return cnt
}
